package logic

import (
	"context"
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"net/http"
	"weee/common"

	"weee/api/internal/svc"
	"weee/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PayLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPayLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PayLogic {
	return &PayLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PayLogic) Pay(req *types.PayRequest) (resp *types.PayResponse, err error) {
	// todo: add your logic here and delete this line
	http.HandleFunc("/notify", func(writer http.ResponseWriter, request *http.Request) {
		request.ParseForm()
		// DecodeNotification 内部已调用 VerifySign 方法验证签名
		var noti, err = common.Client.DecodeNotification(request.Form)
		if err != nil {
			// 错误处理
			fmt.Println(err)
			return
		}
		// 业务处理
		switch noti.TradeStatus {
		case alipay.TradeStatusSuccess:
			fmt.Println("success")
			return
		case alipay.TradeStatusFinished:
			fmt.Println("交易结束，不可退款")
		case alipay.TradeStatusClosed:
			fmt.Println("未付款交易超时关闭，或支付完成后全额退款")
		case alipay.TradeStatusWaitBuyerPay:
			fmt.Println("交易创建，等待买家付款")
		}
		// 如果通知消息没有问题，我们需要确认收到通知消息，不然支付宝后续会继续推送相同的消息
		alipay.ACKNotification(writer)
	})
	fmt.Println("success")
	return
}
